//
//  LCDClockViewController.m
//  CoreAnimationDemo
//
//  Created by 王亮 on 2017/8/8.
//  Copyright © 2017年 王亮. All rights reserved.
//

#import "LCDClockViewController.h"

@interface LCDClockViewController ()
@property (nonatomic, strong)NSMutableArray *digitViews;
@property (nonatomic, strong)NSTimer *timer;

@end

@implementation LCDClockViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.digitViews = [NSMutableArray arrayWithCapacity:0];
    UIImage *image = [UIImage imageNamed:@"lCD"];
    CGFloat width = ([UIScreen mainScreen].bounds.size.height-40)/6;
    for (int i = 0; i < 6; i++) {
        UIView *view = [[UIView alloc] init];
        view.frame = CGRectMake(i*width+20, 100, width, width*2);
        [self.view addSubview:view];
        [self.digitViews addObject:view];
        
        view.layer.contents = (__bridge id _Nullable)(image.CGImage);
        view.layer.contentsRect = CGRectMake(i*0.1, 0, 0.1, 1.0);
        view.layer.contentsGravity = kCAGravityResizeAspect;
        view.layer.magnificationFilter = kCAFilterNearest;
    }
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        //convert time to hours, minutes and seconds
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
        NSUInteger units = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
        
        NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
        
        //set hours
        [self setDigit:components.hour / 10 forView:self.digitViews[0]];
        [self setDigit:components.hour % 10 forView:self.digitViews[1]];
        
        //set minutes
        [self setDigit:components.minute / 10 forView:self.digitViews[2]];
        [self setDigit:components.minute % 10 forView:self.digitViews[3]];
        
        //set seconds
        [self setDigit:components.second / 10 forView:self.digitViews[4]];
        [self setDigit:components.second % 10 forView:self.digitViews[5]];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setDigit:(NSInteger)digit forView:(UIView *)view {
    view.layer.contentsRect = CGRectMake(digit*0.1, 0, 0.1, 1.0);
}
@end
